const moment = require('moment');
const math = require('mathjs');
const accounting = require('accounting');

import db from './datastore';

let fun = {};
fun.insertReport = async function (_taskId,_loopCount){
  let lastTradeList = await db.trade.find({status:1,taskId:_taskId,loopCount:_loopCount});
  let buyMoney = math.chain(0),
      sellMoney = math.chain(0),
      sellAmount = math.chain(0),
      datetime,
      symbol,
      taskId,
      quoteCurrency,
      loopCount;
    for(let i in lastTradeList){
        let item = lastTradeList[i];

        let money = item.money;
        symbol = item.symbol;
        taskId = item.taskId;
        quoteCurrency = item.quoteCurrency;
        loopCount = item.loopCount;
        if(item.direction == 'buy'){
          buyMoney = buyMoney.add(money);
        }else if(item.direction == 'sell'){
          sellMoney = sellMoney.add(money);
          sellAmount = sellAmount.add(item.amount);
          datetime = item.createdAt;
        }
    }

  let profit = sellMoney.subtract(buyMoney.done());
  let profitPercent =  profit.divide(buyMoney.done()).multiply(100);
  profitPercent = accounting.formatNumber(profitPercent.done(),2)
  let item = {
    taskId:taskId,
    quoteCurrency:quoteCurrency,
    loopCount:loopCount,
    symbol:symbol,
    buyMoney:buyMoney.done(),
    sellMoney:sellMoney.done(),
    sellAmount:sellAmount.done(),
    profit:profit.done(),
    profitPercent:profitPercent,
    datetime:moment(datetime).unix(),
    formatDateTime:moment(datetime).format('YYYY-MM-DD HH:mm:ss')
  }
  db.report.insert(item);

}


export default fun


